package org.scboy.common.dynamic.node.sqlNode;

import org.scboy.common.annotation.ScriptNode;
import org.scboy.common.dynamic.node.BaseNode;
import org.scboy.coobi.caches.DbTableCache;
import org.scboy.utils.entitys.coobi.Model;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

@ScriptNode("DB_TABLE_INSERT")
public class DbTableInsertNode extends BaseNode {

	private String dbTable;
	
	@Override
	public void create(JSONObject object) {
		dbTable=object.getStr("dbTable");
	}

	@Override
	public Object run() {
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("----->开始执行："+getNodeName()+" 节点ID："+this.getId());
		}
		
		if(StrUtil.isEmpty(dbTable)) {
			throw new RuntimeException(getNodeName()+"：没有数据表，无法执行。");
		}
		
		if(!DbTableCache.check(dbTable)) {
			throw new RuntimeException(getNodeName()+"：在内存中找不到表"+dbTable+"的配置信息。");
		}
		
		/**
		 * 流出节点
		 */
		BaseNode runTo = getRunTo("to");
		
		Model params=getSourceData("params", true, Model.class);
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("插入数据：\r\n"+entityToString(params));
		}
		//执行Sql
		int count=this.script.getFactory().getDao(dbTable).insert(params);
		this.setData("count", count);
		
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("执行结果："+count);
			this.script.appendMsg("缓存数据：\r\n"+entityToString(this.getDataAll()));
			this.script.appendMsg("执行下个节点："+runTo.getNodeName()+" 节点ID："+runTo.getId());
		}
		return runTo.run();
	}

}
